//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";

import type { RoadmapInfo } from "@/api/roadmap";
import { list_pub, list_my, remove as remove_my_roadmap, update_pub_state } from "@/api/roadmap";
import { request } from "@/utils/request";
import { Button, Card, List, message, Modal, Popover, Segmented, Space } from "antd";
import { openRoadmapView } from "@/utils/roadmap";
import { ExportOutlined, MoreOutlined } from "@ant-design/icons";
import moment from "moment";
import { listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';

import EditRoadmapModal from "./components/EditRoadmapModal";
import { set_access } from "@/api/roadmap_user";

const PAGE_SIZE = 24;

interface RoadmapListPanelProps {
    sourceType: "pub" | "my";
    dataVersion: number;
    keyword: string;
    onUpdate?: () => void;
    onRemove?: () => void;
}

const RoadmapListPanel = (props: RoadmapListPanelProps) => {
    const userStore = useStores('userStore');
    const appStore = useStores('appStore');

    const [roadmapList, setRoadmapList] = useState<RoadmapInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [dataVersion] = useState(props.dataVersion);

    const [updateRoadmapInfo, setUpdateRoadmapInfo] = useState<RoadmapInfo | null>(null);
    const [removeRoadmapInfo, setRemoveRoadmapInfo] = useState<RoadmapInfo | null>(null);


    const loadRoadmapList = async () => {
        if (props.sourceType == "pub") {
            const filterTag = appStore.vendorCfg?.grow_center.filter_tag ?? "";
            const res = await request(list_pub({
                session_id: userStore.sessionId,
                filter_by_keyword: props.keyword != "",
                keyword: props.keyword,
                filter_by_tag: filterTag != "",
                tag: filterTag,
                offset: curPage * PAGE_SIZE,
                limit: PAGE_SIZE,
            }));
            setTotalCount(res.total_count);
            setRoadmapList(res.roadmap_list);
        } else if (props.sourceType == "my") {
            const res = await request(list_my({
                session_id: userStore.sessionId,
                filter_by_keyword: props.keyword != "",
                keyword: props.keyword,
                filter_by_tag: false,
                tag: "",
                offset: curPage * PAGE_SIZE,
                limit: PAGE_SIZE,
            }));
            setTotalCount(res.total_count);
            setRoadmapList(res.roadmap_list);
        }
    };

    const openRoadmapWindow = async (roadmapId: string, roadmapName: string, canUpdate: boolean) => {
        await openRoadmapView(roadmapId, roadmapName, userStore.sessionId, false, canUpdate);
    };

    const removeRoadmap = async () => {
        if (removeRoadmapInfo == null) {
            return;
        }
        await request(remove_my_roadmap({
            session_id: userStore.sessionId,
            roadmap_id: removeRoadmapInfo.roadmap_id,
        }));
        setRemoveRoadmapInfo(null);
        await loadRoadmapList();
        message.info("删除成功");
        if (props.onRemove != undefined) {
            props.onRemove();
        }
    };

    const onAccessRoadmap = async (notice: NoticeType.client.AccessRoadmapNotice) => {
        if (userStore.sessionId == "") {
            return;
        }
        await request(set_access({
            session_id: userStore.sessionId,
            roadmap_id: notice.roadmapId,
            done_topic_count: notice.doneTopicCount,
            total_topic_count: notice.totalTopicCount,
            done_sub_topic_count: notice.doneSubTopicCount,
            total_sub_topic_count: notice.totalSubTopicCount,
        }));
    }

    const updatePubState = async (roadmapId: string, pubState: boolean) => {
        await request(update_pub_state({
            session_id: userStore.sessionId,
            roadmap_id: roadmapId,
            pub_state: pubState,
        }));
        message.info(`设置为${pubState ? "已发布" : "未发布"}状态`);
        await loadRoadmapList();
    };

    useEffect(() => {
        loadRoadmapList();
    }, [props.sourceType, curPage]);

    useEffect(() => {
        if (props.dataVersion == dataVersion) {
            return;
        }
        if (curPage != 0) {
            setCurPage(0);
        } else {
            loadRoadmapList();
        }
    }, [props.dataVersion]);

    useEffect(() => {
        if (curPage != 0) {
            setCurPage(0);
        } else {
            loadRoadmapList();
        }
    }, [props.keyword]);


    useEffect(() => {
        if (userStore.sessionId == "") {
            return;
        }
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.ClientNotice?.AccessRoadmapNotice !== undefined) {
                onAccessRoadmap(notice.ClientNotice.AccessRoadmapNotice);
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, [userStore.sessionId]);

    return (
        <>
            <List rowKey="roadmap_id" dataSource={roadmapList} grid={{ gutter: 16 }}
                style={{ height: "calc(100vh - 130px)", overflowY: "scroll", padding: "10px 10px", overflowX: "hidden" }}
                pagination={{ current: curPage + 1, total: totalCount, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true }}
                renderItem={roadmapItem => (
                    <List.Item>
                        <Card title={
                            <Button type="link" icon={<ExportOutlined />}
                                title={userStore.sessionId == "" ? "登录后才能访问" : ""}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    if (userStore.sessionId == "") {
                                        userStore.showUserLogin = true;
                                    } else {
                                        openRoadmapWindow(roadmapItem.roadmap_id, roadmapItem.basic_info.title, roadmapItem.user_perm.can_update_content);
                                    }
                                }}>
                                {roadmapItem.basic_info.title}
                            </Button>}
                            style={{ width: "320px" }} headStyle={{ backgroundColor: "#eee", padding: "0px 0px" }}
                            bodyStyle={{ height: "100px", overflowY: "scroll" }}
                            extra={
                                <Space style={{ marginRight: "20px" }}>
                                    {props.sourceType == "my" && (
                                        <>
                                            {moment(roadmapItem.update_time).format("YYYY-MM-DD")}
                                            {roadmapItem.user_perm.can_update_pub_state && (
                                                <Segmented options={[
                                                    {
                                                        label: "未发布",
                                                        value: "unpub",
                                                    },
                                                    {
                                                        label: <span style={{ color: roadmapItem.pub_state ? "orange" : "black", fontWeight: roadmapItem.pub_state ? 700 : 500 }}>已发布</span>,
                                                        value: "pub",
                                                    }
                                                ]} value={roadmapItem.pub_state ? "pub" : "unpub"}
                                                    onChange={value => updatePubState(roadmapItem.roadmap_id, value == "pub")} />
                                            )}
                                            <Popover placement="bottom" trigger="click" content={
                                                <Space direction="vertical">
                                                    <Button type="link" onClick={e => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        setUpdateRoadmapInfo(roadmapItem);
                                                    }}>更新</Button>
                                                    <Button type="link" danger onClick={e => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        setRemoveRoadmapInfo(roadmapItem);
                                                    }}>删除</Button>
                                                </Space>
                                            }>
                                                <MoreOutlined />
                                            </Popover>
                                        </>
                                    )}
                                </Space>
                            }>
                            <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>{roadmapItem.basic_info.desc}</pre>
                        </Card>
                    </List.Item>
                )} />
            {updateRoadmapInfo != null && (
                <EditRoadmapModal roadmap={updateRoadmapInfo} onCancel={() => setUpdateRoadmapInfo(null)} onOk={() => {
                    setUpdateRoadmapInfo(null);
                    loadRoadmapList();
                    if (props.onUpdate != undefined) {
                        props.onUpdate();
                    }
                }} />
            )}
            {removeRoadmapInfo != null && (
                <Modal open title="删除路线图" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveRoadmapInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeRoadmap();
                    }}>
                    是否删除路线图&nbsp;{removeRoadmapInfo.basic_info.title}&nbsp;?
                </Modal>
            )}
        </>
    );
};

export default observer(RoadmapListPanel);